﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using Qy.Core;
using Qy.Scenario;
using Qy.Web.Authorize;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Qy.Web.Areas.Api;

[Route("Api/[controller]/[action]")]
[Verify]
public class DocPostController : Base
{
    private readonly ApplicationContext _applicationContext;
    private readonly DocPostService _docPostService;
    private readonly UserService _adminUserService;
    private readonly DocCatService _docCatService;
    private readonly AttmentService _attment;
    public DocPostController(ApplicationContext applicationContext, DocPostService docPostService, DocCatService docCatService,
        AttmentService attmentService, UserService adminUserService)
    {
        _applicationContext = applicationContext;
        _docPostService = docPostService;
        _docCatService = docCatService;
        _attment = attmentService;
        _adminUserService = adminUserService;
    }
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.DocPost_Index)]
    public async Task<IActionResult> IndexAsync([FromQuery] QueryDocPost query, int cid = 0)
    {
        ILoginUserInfo user = await _applicationContext.ILoginUserInfoMethods.LoginUserInfoAsync();
        query.Cids = cid == 0 ? null : new int[] { cid };
        query.Uids = await _adminUserService.UserPostAsUids(user);
        IEnumerable<DocCat> catList = await _docCatService.CategoryListAsync(user, (int)ModelTypeEnum.ModelType.信息报送);
        PagedInfo<ViewDocPostAndCate> pagedList = await _docPostService.GetListByCidAdminAsync(query);
        return Success(new { count = pagedList.TotalNum, data = pagedList.Result, catList });
    }
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.DocPost_AddOrEditView)]
    public async Task<IActionResult> AddOrEditAsync(int id, int cid = 0)
    {
        DocCat docCat = cid > 0 ? await _docCatService.GetInfo(cid) : null;
        if (id > 0)
        {
            EditDocPostAndContent data = await _docPostService.GetEditAsync(id);
            List<Attment> attments = null;
            if (!string.IsNullOrEmpty(data.Attments))
            {
                List<int> attIds = data.Attments.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();
                attments = await _attment.GetListAsync(attIds);
            }
            return Success(new { data, attments, docCat });
        }
        else
        {
            int newNumber = await _docPostService.GetByCidAsync(cid);
            //查询自己最新一条
            DocPost lastDoc = await _docPostService.GetByUidAsync(_applicationContext.ILoginUserInfoMethods.LoginUserId(), cid);
            return Success(new { docCat, lastDoc, newNumber });
        }
    }
    [HttpPost, ActionName("Create")]
    [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.DocPost_AddOrEdit)]
    [Log(Name = "新增发文")]
    public async Task<IActionResult> CreateAsync([FromBody] EditDocPostAndContent post)
    {
        ILoginUserInfo adminUser = await _applicationContext.ILoginUserInfoMethods.LoginUserInfoAsync();
        post.Uid = adminUser.UserId;
        DocPost docPost = post.Adapt<DocPost>();
        DocPostContent docPostContent = post.Adapt<DocPostContent>();
        int resId = await _docPostService.InsertAndDataAsync(docPost, docPostContent);
        if (resId > 0)
            return Success($"新增发文:{post.Title}; Id: {post.Id}");
        else return Fail("新增失败！");
    }
    [HttpPut, ActionName("Edit")]
    [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.DocPost_AddOrEdit)]
    [Log(Name = "修改发文")]

    public async Task<IActionResult> EditAsync([FromBody] EditDocPostAndContent post)
    {
        ILoginUserInfo userInfo = await _applicationContext.ILoginUserInfoMethods.LoginUserInfoAsync();
        if (userInfo.GroupId != 1 && userInfo.UserId != post.Uid)
            return Fail("不能修改别人的内容！");
        DocPost docPost = post.Adapt<DocPost>();
        DocPostContent docPostContent = post.Adapt<DocPostContent>();
        if (0 < await _docPostService.UpdateAndContentAsync(docPost, docPostContent))
            return Success($"修改发文:{post.Title} ID：{post.Id}");
        else return Fail("修改失败！");
    }

    [HttpDelete]
    [ActionPermissionFilter(Permission = PermissionKeys.DocPost_Delete)]
    [Log(Name = "删除发文")]
    public async Task<IActionResult> Delete(int id)
    {
        if (await _docPostService.DelAndContentAsync(id) > 0)
            return Success($"删除发文 ID：{id}");
        else return Fail("删除失败！");
    }

}
